const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    id: null,
    form: {
      model_id: '',
      process_id: '',
      price: '',
      time_price: '',
      status: 1
    },
    modelIndex: 0,
    processIndex: 0,
    statusIndex: 0,
    modelOptions: [{ id: '', name: '请选择产品型号' }],
    processOptions: [{ id: '', name: '请选择工序' }],
    statusOptions: ['禁用', '启用'],
    loading: false
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/process-price-detail/process-price-detail')) {
      return
    }
    
    this.loadModels()
    this.loadProcesses()
    if (options.id) {
      this.setData({
        id: options.id
      })
      this.loadData()
    }
  },

  async loadModels() {
    try {
      const res = await api.getProductModelList({
        status: 1
      })

      if (res.code === 1) {
        const models = res.data.list.map(item => ({
          id: item.id,
          name: `${item.product ? item.product.name : ''} - ${item.name}`
        }))
        
        this.setData({
          modelOptions: [{ id: '', name: '请选择产品型号' }, ...models]
        })
      }
    } catch (error) {
      console.error('加载型号列表失败:', error)
    }
  },

  async loadProcesses() {
    try {
      const res = await api.getProcessList({
        status: 1
      })

      if (res.code === 1) {
        const processes = res.data.list.map(item => ({
          id: item.id,
          name: item.name
        }))
        
        this.setData({
          processOptions: [{ id: '', name: '请选择工序' }, ...processes]
        })
      }
    } catch (error) {
      console.error('加载工序列表失败:', error)
    }
  },

  async loadData() {
    try {
      const res = await api.getProcessPriceList({
        id: this.data.id
      })

      if (res.code === 1 && res.data.list.length > 0) {
        const item = res.data.list[0]
        const modelIndex = this.data.modelOptions.findIndex(m => m.id == item.model_id)
        const processIndex = this.data.processOptions.findIndex(p => p.id == item.process_id)
        
        this.setData({
          form: {
            model_id: item.model_id,
            process_id: item.process_id,
            price: item.price,
            time_price: item.time_price || '',
            status: item.status
          },
          modelIndex: modelIndex > 0 ? modelIndex : 0,
          processIndex: processIndex > 0 ? processIndex : 0,
          statusIndex: item.status === 1 ? 1 : 0
        })
      }
    } catch (error) {
      console.error('加载工价详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  onModelChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      modelIndex: index,
      'form.model_id': this.data.modelOptions[index].id
    })
  },

  onProcessChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      processIndex: index,
      'form.process_id': this.data.processOptions[index].id
    })
  },

  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value),
      'form.status': parseInt(e.detail.value)
    })
  },

  async onSubmit(e) {
    if (this.data.loading) return

    // 检查权限
    const action = this.data.id ? 'edit' : 'add'
    if (!this.hasPermission('price_manage', action)) {
      wx.showToast({
        title: `您没有${this.data.id ? '编辑' : '新增'}权限`,
        icon: 'none'
      })
      return
    }

    const formData = e.detail.value
    
    if (!formData.price || parseFloat(formData.price) <= 0) {
      wx.showToast({
        title: '请输入有效的计件工价',
        icon: 'none'
      })
      return
    }

    if (!this.data.form.model_id) {
      wx.showToast({
        title: '请选择产品型号',
        icon: 'none'
      })
      return
    }

    if (!this.data.form.process_id) {
      wx.showToast({
        title: '请选择工序',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    try {
      const data = {
        model_id: this.data.form.model_id,
        process_id: this.data.form.process_id,
        price: parseFloat(formData.price),
        time_price: formData.time_price ? parseFloat(formData.time_price) : 0,
        status: this.data.form.status
      }

      let res
      if (this.data.id) {
        data.id = this.data.id
        res = await api.updateProcessPrice(data)
      } else {
        res = await api.createProcessPrice(data)
      }

      if (res.code === 1) {
        wx.showToast({
          title: this.data.id ? '更新成功' : '创建成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('保存工价失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  onCancel() {
    wx.navigateBack()
  },

  // 检查是否有权限执行某个操作
  hasPermission(module, action) {
    // 从session中获取管理员信息
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    if (!adminInfo || !adminInfo.id) {
      return false;
    }
    
    // 使用权限工具检查权限（基于管理组）
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  }
})
